package com.microsoft.dpe.uk.embeddedworkitems;

import java.util.ArrayList;

public class Logic 
{
	/**
	 * Return the work item ids from a String. The work items are enclosed with square brackets, and are numeric.
	 *  
	 * @param theComment The String from which to extract the work item ids
	 * @return An array of work item id as Integers
	 */
	public static Integer[] getWorkItemIds(String theComment)
     {
         final String START_MARKER = "\\[";
         final String END_MARKER = "]";

         String[] subStrings = theComment.split(START_MARKER); 
         ArrayList<Integer> workItems = new ArrayList<Integer>();
         
         for (String item : subStrings) 
         { 
             // Want to find a number bounded by the closing marker so as not to pick up an unintended work item
             // e.g. Closed 23 bugs including [123]
             if (item.contains(END_MARKER)) 
             {
                 // Find the position of the end marker
                 int endMarkerIndex = item.indexOf(END_MARKER);
                 // Take the substring from the beginning to the end marker
                 String wiID = item.substring(0, endMarkerIndex);
                 // Remove any white spaces etc
                 wiID = wiID.trim();
                 try
                 {
                     workItems.add(Integer.parseInt(wiID));
                 }
                 catch (NumberFormatException nfEx)
                 {
                     // Swallow exception - it wasn't a number, therefore not a work item id
                 }  
             }
         }

         // Create return array
         Integer[] wiIntegers = new Integer[workItems.size()];
         return workItems.toArray(wiIntegers);        
     }
}
